package org.xm.sk.controller.dbase;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.data.domain.Page;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.xm.sk.common.ToolsUtil;
import org.xm.sk.exception.DataNotFoundException;
import org.xm.sk.exception.RequestParamterException;
import org.xm.sk.service.data.BaseService;
import org.xm.sk.service.security.XmUser;
import org.xm.sk.vo.Base;
import org.xm.sk.vo.e.Datalevel;
import org.xm.sk.vo.ob.HairdresserInfo;
import org.xm.sk.vo.ob.HairdresserSelfInfo;
import org.xm.sk.vo.ob.Ids;
import org.xm.sk.vo.ob.Local;
import org.xm.sk.vo.ob.LocalHairdresserList;
import org.xm.sk.vo.ob.MapList;
import org.xm.sk.vo.ob.PageConf;
import org.xm.sk.vo.ob.PriceInfo;
import org.xm.sk.vo.ob.ResultMsg;
import org.xm.sk.vo.ob.ServerTimeInfo;
import org.xm.sk.vo.ob.WorksInfo;
import org.xm.sk.vo.tb.Activity;
import org.xm.sk.vo.tb.Boder;
import org.xm.sk.vo.tb.Hairdresser;
import org.xm.sk.vo.tb.Image;
import org.xm.sk.vo.tb.Item;
import org.xm.sk.vo.tb.Price;
import org.xm.sk.vo.tb.ServerTime;
import org.xm.sk.vo.tb.Shop;
import org.xm.sk.vo.tb.Sign;
import org.xm.sk.vo.tb.User;
import org.xm.sk.vo.tb.Works;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@SuppressWarnings("unchecked")
@Api(tags = { "hairdresser" })
@RestController
@RequestMapping(value = "/hairdressers")
public class HairdresserController {

    @Autowired
    private MessageSource messages;
    @Autowired
    private BaseService<Hairdresser> hairdresserService;
    @Autowired
    private BaseService<Boder> boderService;
    @Autowired
    private BaseService<Activity> activityService;
    @Autowired
    private BaseService<Shop> shopService;
    @Autowired
    private BaseService<User> userService;
    @Autowired
    private BaseService<Item> itemService;
    @Autowired
    private BaseService<Price> priceService;
    @Autowired
    private BaseService<ServerTime> serverTimeService;
    @Autowired
    private BaseService<Image> imageService;
    @Autowired
    private BaseService<Sign> signService;

    @Transactional
    @ApiOperation(value = "商家端创建/编辑发型师", notes = "根据hairdresser对象创建发型师，使用此接口需要ADMIN/BOSS权限")
    @ApiImplicitParam(name = "hairdresser", value = "发型师详细实体hairdresser", required = true, dataType = "Hairdresser")
    @PreAuthorize("hasAnyRole('ADMIN', 'BOSS')")
    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResultMsg add(@RequestBody Hairdresser hairdresser) {
        Hairdresser u = null;
        if (null != hairdresser.getId() && 0 < hairdresser.getId())
            u = (Hairdresser) hairdresserService.findById(hairdresser.getId());
        else
            u = hairdresser;
        u.setShop(null);
        u.setUser(null);
        if (null != hairdresser.getShopId() && 0 < hairdresser.getShopId()) {
            Shop shop = (Shop) shopService.findById(hairdresser.getShopId());
            if (Base.isValid(shop)) {
                u.setShop(shop);
            }
        }
        if (null != hairdresser.getUserId() && 0 < hairdresser.getUserId()) {
            User user = (User) userService.findById(hairdresser.getUserId());
            if (Base.isValid(user)) {
                /*Set<Role> roles = (Set<Role>) roleService
                        .findByName("ROLE_HAIRDRE");
                user.getRoles().clear();
                user.getRoles().add(roles.iterator().next());
                user = userService.update(user);*/
                u.setUser(user);
            }
        }
        Set<Price> ps = new HashSet<Price>(0);
        if (null != hairdresser.getPriceInfos()
                && !hairdresser.getPriceInfos().isEmpty()) {
            boolean c = true;
            for (PriceInfo pi : hairdresser.getPriceInfos()) {
                if (null != pi.getItemId() && 0 < pi.getItemId()) {
                    Item item = (Item) itemService.findById(pi.getItemId());
                    if (null != item) {
                        if (c) {
                            Set<Integer> ids = new HashSet<Integer>(0);
                            for (Price p : u.getPrices()) {
                                ids.add(p.getId());
                            }
                            u.getPrices().clear();
                            if (!ids.isEmpty())
                                priceService.delete(ids);
                            c = false;
                        }
                        Price p = new Price();
                        p.setName(item.getName());
                        p.setHairdresser(u);
                        p.setItem(item);
                        p.setBrokerage(pi.getBrokerage());
                        p.setPrice(pi.getPrice());
                        ps.add(p);
                    }
                }
            }
        }
        if (null != hairdresser.getServerTimesIds()
                && !hairdresser.getServerTimesIds().isEmpty()) {
            u.getServerTimes().clear();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("findByIdIn", hairdresser.getServerTimesIds());
            Set<ServerTime> sts = (Set<ServerTime>) serverTimeService
                    .findAllByPage(null, map);
            u.getServerTimes().addAll(sts);
        }
        u.setName(hairdresser.getName());
        u.setCmark(hairdresser.getCmark());
        u.getImages().clear();
        if (null != hairdresser.getImageIds()
                && !hairdresser.getImageIds().isEmpty()) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("findByIdIn", hairdresser.getImageIds());
            Set<Image> sts = (Set<Image>) imageService.findAllByPage(null, map);
            u.getImages().addAll(sts);
        }
        if (-1 < u.getName().indexOf(":"))
            u.setName(u.getName().substring(0, u.getName().indexOf(":")));
        u.setMemo(hairdresser.getMemo());
        if (null != u.getId() && 0 < u.getId())
            u = hairdresserService.update(u);
        else
            u = hairdresserService.add(u);
        if (!ps.isEmpty()) {
            for (Price p : ps) {
                p.setHairdresser(u);
                priceService.add(p);
            }
        }
        return new ResultMsg("200",
                messages.getMessage("success", null, "SUCCESS", null),
                new Date());
    }

    @ApiIgnore()
    @ApiOperation(value = "删除发型师", notes = "根据URI的id来指定删除对象")
    @ApiImplicitParam(name = "id", value = "发型师ID", required = true, paramType = "path", dataType = "int")
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public ResultMsg delete(@PathVariable Integer id) {
        hairdresserService.delete(id);
        return new ResultMsg("200",
                messages.getMessage("success", null, "SUCCESS", null),
                new Date());
    }

    @ApiOperation(value = "删除发型师", notes = "根据POST的id列表来指定删除对象，可批量")
    @ApiImplicitParam(name = "ids", value = "发型师ID集", required = true, dataType = "Ids")
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public ResultMsg Batchdelete(@RequestBody Ids ids) {
        hairdresserService.delete(ids.getIds());
        return new ResultMsg("200",
                messages.getMessage("success", null, "SUCCESS", null),
                new Date());
    }

    @ApiIgnore()
    @ApiOperation(value = "更新发型师详细信息", notes = "根据URI的id来指定更新对象，并根据传过来的hairdresser信息来更新发型师详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "发型师ID", required = true, paramType = "path", dataType = "int"),
            @ApiImplicitParam(name = "hairdresser", value = "待更新的发型师详细实体hairdresser", required = true, dataType = "Hairdresser") })
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public ResultMsg update(@PathVariable Integer id,
            @RequestBody Hairdresser hairdresser) throws DataNotFoundException {
        Hairdresser u = (Hairdresser) hairdresserService.findById(id);
        if (null == u) {
            throw new DataNotFoundException(Hairdresser.class.getName());
        }
        hairdresser.setId(id);
        hairdresserService.update(hairdresser);
        return new ResultMsg("200",
                messages.getMessage("success", null, "SUCCESS", null),
                new Date());
    }

    @ApiIgnore()
    @ApiOperation(value = "获取发型师详细信息", notes = "根据URI的id来获取发型师详细信息")
    @ApiImplicitParam(name = "id", value = "发型师ID", required = true, paramType = "path", dataType = "int")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Hairdresser load(@PathVariable Integer id)
            throws DataNotFoundException {
        Hairdresser u = (Hairdresser) hairdresserService.findById(id);
        if (null == u) {
            throw new DataNotFoundException(Hairdresser.class.getName());
        }
        if (null != u.getUser())
            u.setPhone(u.getUser().getPhone());
        return u;
    }

    @ApiOperation(value = "商家端获取发型师列表", notes = "根据提交的分页信息列出所以发型师信息")
    @ApiImplicitParam(name = "pageConf", value = "分页信息实体", required = true, dataType = "PageConf")
    @RequestMapping(value = { "/list" }, method = RequestMethod.POST)
    public MapList<Hairdresser> list(@RequestBody PageConf pageConf) {
        List<Hairdresser> u = null;
        Long allCount = null;
        Object o = hairdresserService.findAllByPage(pageConf);
        if (o instanceof Page) {
            allCount = ((Page<Hairdresser>) o).getTotalElements();
            u = ((Page<Hairdresser>) o).getContent();
        } else {
            allCount = (long) ((List<Hairdresser>) o).size();
            u = (List<Hairdresser>) o;
        }
        for (Hairdresser c : u) {
            if (null != c.getShop()) {
                c.setShopId(c.getShop().getId());
                c.setShopName(c.getShop().getName());
            }
            if (null != c.getUser()) {
                c.setUserId(c.getUser().getId());
                c.setUserName(c.getUser().getName());
                if (null != c.getUser().getPhone()
                        && 0 < c.getUser().getPhone().trim().length())
                    c.setName(c.getName() + ":" + c.getUser().getPhone());
            }
            if (null != c.getFans())
                c.setFansCount(c.getFans().size());
            if (null != c.getPrices() && !c.getPrices().isEmpty()) {
                for (Price p : c.getPrices()) {
                    if (Datalevel.NORMAL == p.getDatalevel()) {
                        PriceInfo pi = new PriceInfo(
                                null != p.getItem() ? p.getItem().getId()
                                        : null,
                                p.getName(), p.getPrice(), p.getBrokerage());
                        c.getPriceInfos().add(pi);
                    }
                }
            }
            if (null != c.getServerTimes() && !c.getServerTimes().isEmpty()) {
                for (ServerTime p : c.getServerTimes()) {
                    if (Datalevel.NORMAL == p.getDatalevel()) {
                        c.getServerTimesIds().add(p.getId());
                    }
                }
            }
        }
        return new MapList<Hairdresser>(allCount, u);
    }

    // --------------------- 业务具体接口 ---------------------

    @ApiOperation(value = "（附近/搜索）发型师列表", notes = "根据提交的分页信息，以（发型师名称为关键字搜索/位置信息为重点列出附近）发型师信息，如果关键字不为空，优先以关键字搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "size", value = "每页数量", required = true, paramType = "path", dataType = "int"),
            @ApiImplicitParam(name = "page", value = "页码", required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "local", value = "位置坐标信息", required = true, dataType = "Local") })
    @PreAuthorize("hasAnyRole('ADMIN', 'CLIENT')")
    @RequestMapping(value = { "/{size}/{page}" }, method = RequestMethod.POST)
    public MapList<LocalHairdresserList> list(@PathVariable Integer size,
            @PathVariable Integer page, @RequestBody Local local)
            throws RequestParamterException {
        if (null == size || null == page || 1 > size || 0 > page) {
            throw new RequestParamterException();
        }
        Page<Hairdresser> hairdressers = (Page<Hairdresser>) hairdresserService
                .findAllByPage(new PageConf(page, size), local);
        Long allCount = hairdressers.getTotalElements();
        List<LocalHairdresserList> result = new ArrayList<LocalHairdresserList>();
        for (int i = 0; i < hairdressers.getContent().size(); i++) {
            Hairdresser hairdresser = hairdressers.getContent().get(i);
            LocalHairdresserList lh = new LocalHairdresserList();
            lh.setId(hairdresser.getId());
            lh.setName(hairdresser.getName());
            lh.setFansCount(hairdresser.getFans().size());
            lh.setCmark(hairdresser.getCmark());
            if (null != hairdresser.getShop()) {
                lh.setShopName(hairdresser.getShop().getName());
                lh.setShopId(hairdresser.getShop().getId());
            }
            if (null != hairdresser.getUser()
                    && null != hairdresser.getUser().getImage())
                lh.setImageId(hairdresser.getUser().getImage().getId());
            Set<Integer> ids = new HashSet<Integer>();
            for (Image image : hairdresser.getImages()) {
                ids.add(image.getId());
            }
            lh.setImageIds(ids);
            XmUser xmUser = (XmUser) SecurityContextHolder.getContext()
                    .getAuthentication().getPrincipal();
            boolean isAt = false;
            Iterator<User> it = hairdresser.getFans().iterator();
            while (it.hasNext()) {
                User user = it.next();
                if (new Integer(xmUser.getUserid()).equals(user.getId())) {
                    isAt = true;
                    break;
                }
            }
            lh.setIsAt(isAt);
            result.add(lh);
        }
        return new MapList<LocalHairdresserList>(allCount, result);
    }

    @ApiOperation(value = "关注发型师", notes = "根据URI的id来进行发型师关注操作")
    @ApiImplicitParam(name = "id", value = "发型师ID", required = true, paramType = "path", dataType = "int")
    @PreAuthorize("hasAnyRole('ADMIN', 'CLIENT')")
    @RequestMapping(value = "/at/{id}", method = RequestMethod.GET)
    public ResultMsg at(@PathVariable Integer id) throws DataNotFoundException {
        Hairdresser u = (Hairdresser) hairdresserService.findById(id);
        if (null == u) {
            throw new DataNotFoundException(Shop.class.getName());
        }
        XmUser xmUser = (XmUser) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();
        User user = (User) userService.findById(xmUser.getUserid());
        if (null == user || Datalevel.NORMAL != user.getDatalevel()) {
            throw new AccessDeniedException("无效令牌信息，查无用户信息");
        }
        u.getFans().add(user);
        hairdresserService.update(u);
        return new ResultMsg("200", "成功关注", new Date());
    }

    @ApiOperation(value = "取消关注发型师", notes = "根据URI的id来进行取消关注发型师操作")
    @ApiImplicitParam(name = "id", value = "发型师ID", required = true, paramType = "path", dataType = "int")
    @PreAuthorize("hasAnyRole('ADMIN', 'CLIENT')")
    @RequestMapping(value = "/ct/{id}", method = RequestMethod.GET)
    public ResultMsg ct(@PathVariable Integer id) throws DataNotFoundException {
        Hairdresser u = (Hairdresser) hairdresserService.findById(id);
        if (null == u) {
            throw new DataNotFoundException(Shop.class.getName());
        }
        XmUser xmUser = (XmUser) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();
        User user = (User) userService.findById(xmUser.getUserid());
        if (null == user || Datalevel.NORMAL != user.getDatalevel()) {
            throw new AccessDeniedException("无效令牌信息，查无用户信息");
        }
        u.getFans().remove(user);
        hairdresserService.update(u);
        return new ResultMsg("200", "成功取消关注", new Date());
    }

    @ApiOperation(value = "获取发型师详细信息", notes = "根据URI的id和提交的位置信息来获取发型师详细信息，其中包括动态的距离信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "发型师ID", required = true, paramType = "path", dataType = "int"),
            @ApiImplicitParam(name = "local", value = "位置坐标信息", required = true, dataType = "Local") })
    @PreAuthorize("hasAnyRole('ADMIN', 'CLIENT')")
    @RequestMapping(value = "/{id}", method = RequestMethod.POST)
    public HairdresserInfo load(@PathVariable Integer id,
            @RequestBody Local local) throws DataNotFoundException {
        Hairdresser u = (Hairdresser) hairdresserService.findById(id);
        if (null == u) {
            throw new DataNotFoundException(Shop.class.getName());
        }
        HairdresserInfo hairdresserInfo = new HairdresserInfo();
        Double distance = ToolsUtil.distance(local,
                new Local(u.getShop().getLatitude(), u.getShop().getLongitude(),
                        null, null));
        hairdresserInfo.setId(u.getId());
        hairdresserInfo.setName(u.getName());
        hairdresserInfo.setFansCount(u.getFans().size());
        hairdresserInfo.setCmark(u.getCmark());
        hairdresserInfo.setMemo(u.getMemo());
        if (null != u.getShop()) {
            hairdresserInfo.setShopId(u.getShop().getId());
            hairdresserInfo.setShopName(u.getShop().getName());
        }
        if (null != u.getUser() && null != u.getUser().getImage())
            hairdresserInfo.setImageId(u.getUser().getImage().getId());
        Set<Integer> ids = new HashSet<Integer>();
        for (Image image : u.getImages()) {
            ids.add(image.getId());
        }
        hairdresserInfo.setImageIds(ids);
        XmUser xmUser = (XmUser) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();
        boolean isAt = false;
        Iterator<User> it = u.getFans().iterator();
        while (it.hasNext()) {
            User user = it.next();
            if (new Integer(xmUser.getUserid()).equals(user.getId())) {
                isAt = true;
                break;
            }
        }
        hairdresserInfo.setIsAt(isAt);
        hairdresserInfo.setShopAddress(u.getShop().getAddress());
        hairdresserInfo.setDistance(distance);
        Set<WorksInfo> worksInfos = new HashSet<WorksInfo>(0);
        for (Works works : u.getWorkses()) {
            if (Datalevel.NORMAL != works.getDatalevel())
                continue;
            WorksInfo ws = new WorksInfo();
            ws.setId(works.getId());
            ws.setName(works.getName());
            ws.setContent(works.getContent());
            ws.setCreatedate(works.getCreatedate());
            ws.setWtype(works.getWtype());
            if (null != works.getImage())
                ws.setImageId(works.getImage().getId());
            worksInfos.add(ws);
        }
        hairdresserInfo.setWorksInfos(worksInfos);
        if (null != u.getUser())
            hairdresserInfo.setPhone(u.getUser().getPhone());
        return hairdresserInfo;
    }

    @ApiOperation(value = "发型师端获取自己的详细信息", notes = "此接口只允许管理员和发型师调用，并必须有发型师相关信息才能正常使用")
    @PreAuthorize("hasAnyRole('ADMIN', 'HAIRDRE')")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public HairdresserSelfInfo loadSelf() throws RequestParamterException {
        XmUser xmUser = (XmUser) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();
        User user = (User) userService.findById(xmUser.getUserid());
        if (!Base.isValid(user) || Datalevel.NORMAL != user.getDatalevel())
            throw new AccessDeniedException("无效令牌信息，查无用户信息");
        Boolean isSign = false;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("isSignUserId", user.getId());
        Long l = (Long) userService.findAllByPage(null, map);
        if (null != l && 0 < l)
            isSign = true;
        if (0 == xmUser.getHairdresserid()) {
            throw new RequestParamterException("当前用户非发型师用户，查无发型师信息");
        }
        map.clear();
        map.put("hairdresserid", xmUser.getHairdresserid());
        HairdresserSelfInfo u = (HairdresserSelfInfo) hairdresserService
                .findAllByPage(null, map);
        u.setIsSign(isSign);
        return u;
    }

    @ApiOperation(value = "发型师端获取关注自己的粉丝列表", notes = "此接口只允许管理员和发型师调用，并必须有发型师相关信息才能正常使用")
    @PreAuthorize("hasAnyRole('ADMIN', 'HAIRDRE')")
    @ApiImplicitParam(name = "pageConf", value = "分页信息实体", required = true, dataType = "PageConf")
    @RequestMapping(value = "/info/fans", method = RequestMethod.POST)
    public MapList<User> loadSelfFansList(@RequestBody PageConf pageConf)
            throws RequestParamterException {
        XmUser xmUser = (XmUser) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();
        User user = (User) userService.findById(xmUser.getUserid());
        if (!Base.isValid(user) || Datalevel.NORMAL != user.getDatalevel())
            throw new AccessDeniedException("无效令牌信息，查无用户信息");
        if (0 == xmUser.getHairdresserid()) {
            throw new RequestParamterException("当前用户非发型师用户，查无发型师信息");
        }
        // 在这里判断有没传优惠活动Id进来，如果有，判断优惠活动的状态和附属情况
        if (null != pageConf.getDataMap()
                && pageConf.getDataMap().containsKey("activityId")
                && null != pageConf.getDataMap().get("activityId")
                && 0 < Integer.valueOf(
                        pageConf.getDataMap().get("activityId").toString())) {
            Integer activityId = Integer.valueOf(
                    pageConf.getDataMap().get("activityId").toString());
            Activity c = (Activity) activityService.findById(activityId);
            if (!(Base.isValid(c) && c.getDatalevel() == Datalevel.NORMAL && c.getDeadline().getTime() > (new Date()).getTime()))
                throw new RequestParamterException("无效优惠活动");
            if (1 > (c.getCount() - c.getCoupons().size())) {
                throw new RequestParamterException("抱歉！此优惠活动已无优惠券可领取");
            }
            if (null == c.getHairdresser() || c.getHairdresser().getId() != xmUser.getHairdresserid())
                throw new RequestParamterException("抱歉！此优惠活动非此发型师的优惠活动");
        }
        pageConf.getDataMap().put("hairdresserId",
                xmUser.getHairdresserid() + "");
        List<User> u = null;
        Long allCount = null;
        Object o = userService.findAllByPage(pageConf);
        if (o instanceof Page) {
            allCount = ((Page<User>) o).getTotalElements();
            u = ((Page<User>) o).getContent();
        } else {
            allCount = (long) ((List<User>) o).size();
            u = (List<User>) o;
        }
        for (User ur : u) {
            ur.setImageId(user.getImage().getId());
        }
        return new MapList<User>(allCount, u);
    }

    @ApiOperation(value = "获取关注的发型师列表", notes = "此接口只允许管理员和客户调用，返回用户关注的发型师列表信息")
    @ApiImplicitParam(name = "pageConf", value = "分页信息实体", required = true, dataType = "PageConf")
    @PreAuthorize("hasAnyRole('ADMIN', 'CLIENT')")
    @RequestMapping(value = "/at/list", method = RequestMethod.POST)
    public MapList<HairdresserSelfInfo> atList(@RequestBody PageConf pageConf)
            throws DataNotFoundException {
        XmUser xmUser = (XmUser) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userid", xmUser.getUserid());
        Page<HairdresserSelfInfo> u = (Page<HairdresserSelfInfo>) hairdresserService
                .findAllByPage(pageConf, map);
        Long allCount = u.getTotalElements();
        return new MapList<HairdresserSelfInfo>(allCount, u.getContent());
    }

    @ApiOperation(value = "获取指定发型师一周内服务时间列表", notes = "返回发型师一周内每天服务的时间点列表")
    @ApiImplicitParam(name = "id", value = "发型师ID", required = true, paramType = "path", dataType = "int")
    @RequestMapping(value = "/stime/list/{id}", method = RequestMethod.GET)
    public List<ServerTimeInfo> sTimeList(@PathVariable Integer id)
            throws RequestParamterException {
        if (null == id || 1 > id) {
            throw new RequestParamterException();
        }
        Hairdresser hairdresser = (Hairdresser) hairdresserService.findById(id);
        if (null == hairdresser) {
            throw new RequestParamterException("查无发型师信息");
        }
        List<String> sDates = new ArrayList<String>(0);
        for (int i = 0; i < 7; i++) {
            Calendar now = Calendar.getInstance();
            now.add(Calendar.DATE, i);
            sDates.add(
                    new SimpleDateFormat("yyyy-MM-dd").format(now.getTime()));
        }
        Set<ServerTime> stimes = hairdresser.getServerTimes();
        List<ServerTimeInfo> result = new ArrayList<ServerTimeInfo>(0);
        for (int i = 0; i < 7; i++) {
            List<ServerTime> lt = new ArrayList<ServerTime>(0);
            for (ServerTime st : stimes) {
                if (Datalevel.NORMAL == st.getDatalevel()) {
                    ServerTime sst = new ServerTime();
                    ToolsUtil.cleanDao4Query(sst);
                    sst.setId(null);
                    sst.setDatalevel(null);
                    sst.setName(st.getName());
                    lt.add(sst);
                }
            }
            Collections.sort(lt, new Comparator<ServerTime>() {
                public int compare(ServerTime arg0, ServerTime arg1) {
                    return arg0.getName().compareTo(arg1.getName());
                }
            });
            result.add(new ServerTimeInfo(sDates.get(i), lt));
        }
        Date now = new Date();
        String date = new SimpleDateFormat("yyyy-MM-dd").format(now);
        String time = (new SimpleDateFormat("yyyy-MM-dd HH:mm").format(now))
                .replaceAll(date + " ", "");
        for (ServerTimeInfo sti : result) {
            if (sti.getDate().equals(date)) {
                for (ServerTime st : sti.getTimes()) {
                    try {
                        Date d = new SimpleDateFormat("yyyy-MM-dd HH:mm")
                                .parse(sti.getDate() + " " + st.getName());
                        if (d.getTime() <= now.getTime()) {
                            st.setStatus(1);
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("hairdresserid", id);
        map.put("queryServerTime", "");
        List<ServerTimeInfo> serverTimeInfoList = (List<ServerTimeInfo>) boderService
                .findAllByPage(null, map);
        for (ServerTimeInfo s : serverTimeInfoList) {
            date = new SimpleDateFormat("yyyy-MM-dd").format(s.getStime());
            time = (new SimpleDateFormat("yyyy-MM-dd HH:mm")
                    .format(s.getStime())).replaceAll(date + " ", "");
            for (ServerTimeInfo sti : result) {
                if (sti.getDate().equals(date)) {
                    for (ServerTime st : sti.getTimes()) {
                        if (time.equals(st.getName())) {
                            st.setStatus(0);
                        }
                    }
                }
            }
        }
        return result;
    }

    @ApiOperation(value = "发型师签到", notes = "此接口只允许发型师端适用，进行发型师签到操作")
    @PreAuthorize("hasAnyRole('ADMIN', 'HAIRDRE')")
    @RequestMapping(value = "/sign", method = RequestMethod.GET)
    public ResultMsg sign() throws DataNotFoundException {
        XmUser xmUser = (XmUser) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();
        User user = (User) userService.findById(xmUser.getUserid());
        if (!Base.isValid(user) || Datalevel.NORMAL != user.getDatalevel())
            throw new AccessDeniedException("无效令牌信息，查无用户信息");
        Sign sign = new Sign();
        sign.setUser(user);
        sign.setSignTime(new Date());
        signService.add(sign);
        return new ResultMsg("200",
                messages.getMessage("success", null, "SUCCESS", null),
                new Date());
    }

}
